package uniriotec.pm.empresa.listener;

import java.net.URL;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.log4j.Appender;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.xml.DOMConfigurator;

/**
 * Application Lifecycle Listener implementation class LoadLog4JConfigurationsListener
 * Este listener � utilizado apenas para carregar as configura��es do log4j.xml.
 *
 */
public class LoadLog4JConfigurationsListener implements ServletContextListener {

    private static final String LOGGER_ID = "INIT_LOG_CONFIGURATION";

	private static final Logger LOG;

	static {
		LOG = Logger.getLogger(LOGGER_ID);
		Appender appender = new ConsoleAppender( new PatternLayout("%-5p [%d] [%C{1}.%M:%L] %m%n"), "System.out");
		LOG.setAdditivity(false);
		LOG.addAppender(appender);
		LOG.setLevel(Level.DEBUG);
	}

	/**
     * Default constructor.
     */
    public LoadLog4JConfigurationsListener() {
    }

	/**
     * @see ServletContextListener#contextInitialized(ServletContextEvent)
     * Carrega as configura��es do log4j.xml durante o deployment da aplica��o
     */
    public void contextInitialized(ServletContextEvent arg0) {
    	LOG.debug("Inicializando a configura��o do Log4J ...");
    	ClassLoader loader = Thread.currentThread().getContextClassLoader();
		URL url = loader.getResource("log4j.xml");
		if (url == null) {
			url = this.getClass().getClassLoader().getResource("log4j.xml");
		}
		if (url == null) {
			url = this.getClass().getResource("log4j.xml");
		}
    	DOMConfigurator.configure(url);
	}

	/**
     * @see ServletContextListener#contextDestroyed(ServletContextEvent)
     */
    public void contextDestroyed(ServletContextEvent arg0) {
    }

}
